//
//  PhotoEditPreviewViewController.m
//  XPhoto
//
//  Created by baboy on 2019/5/28.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PhotoEditPreviewViewController.h"
#import "BKImageView.h"
#import "PhotoAsset.h"
#import "PHAsset+x.h"
#import <AFNetworking/UIImageView+AFNetworking.h>
#import "BKPlayerView.h"

@interface PhotoEditPreviewViewController ()<UIScrollViewDelegate>
@property(nonatomic, strong) NSOperationQueue *photoLoadQueue;
@property(nonatomic, strong) NSMutableDictionary *photoLoadOperationPool;
@end

@implementation PhotoEditPreviewViewController
- (void)dealloc{
    [self.photoLoadQueue cancelAllOperations];
}
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
        
    }
    return self;
}
- (id)initWithPhotos:(NSArray*)photos{
    if (self = [self init]) {
        if (photos) {
            self.photos = [NSMutableArray arrayWithArray:photos];
        }
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    DLOG(@"%@,contentView:%@", NSStringFromCGRect(self.view.bounds), NSStringFromCGRect(self.contentView.bounds));
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"back", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"remove", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(removePhoto:)];
//    [self performSelector:@selector(toggleNavigationBar) withObject:nil afterDelay:3.0f];
    self.contentView.delegate = self;
    self.photoLoadQueue = [[NSOperationQueue alloc] init];
    self.photoLoadQueue.maxConcurrentOperationCount = 1;
    self.photoLoadOperationPool = [NSMutableDictionary dictionary];
    self.pageControl.numberOfPages = self.photos.count;
    self.pageControl.currentPage = self.defaultPage;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupViews];
    DLOG(@"viewWillAppear:%@,contentView:%@", NSStringFromCGRect(self.view.bounds), NSStringFromCGRect(self.contentView.bounds));
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    DLOG(@"viewDidAppear:%@,contentView:%@", NSStringFromCGRect(self.view.bounds), NSStringFromCGRect(self.contentView.bounds));
    
}

- (BKPlayerView *)createPlayerWithFrame:(CGRect)frame photo:(PhotoAsset *)photoAsset{
    BKPlayerView *view = [BKPlayerView view];
    view.shouldAutoPlay = NO;
    view.showControls = YES;
    view.frame = frame;
    if (photoAsset.originImage) {
        view.coverImage = photoAsset.originImage;
    }
    if (photoAsset.originPath) {
        view.videoURL = [NSURL fileURLWithPath:photoAsset.originPath];
    }
    return view;
}

- (UIImageView *)createImageViewWithFrame:(CGRect)frame photo:(PhotoAsset *)photoAsset{
    BKImageView *imageView = [[BKImageView alloc] initWithFrame:frame];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    imageView.clipsToBounds = YES;
    [imageView addTarget:self action:@selector(clickPhoto:)];

    if (photoAsset.originImage) {
        imageView.image = photoAsset.originImage;
    }else if (photoAsset.originPath) {
        [imageView setImageWithURL:[NSURL fileURLWithPath:photoAsset.originPath]];
    }else if (photoAsset.asset) {
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
            
            //            dispatch_async(dispatch_get_main_queue(), ^{
            //            });
            //            return;
            [photoAsset.asset loadHighQualityImageWithProgressHandler:^(double progress, NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    DLOG(@"%@,%f", photoAsset.asset.localIdentifier, progress);
                });
                
            }
                                                                   resultHandler:^(UIImage * _Nonnull result, NSDictionary * _Nonnull info) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = result;
                });
            }];
        }];
        [self.photoLoadQueue addOperation:operation];
        [self.photoLoadOperationPool setObject:operation forKey:photoAsset.asset.localIdentifier];
        
    }
    return imageView;
}

- (void)setupViews{
    if (self.photoViews) {
        [self.photoViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    self.photoViews = [NSMutableArray array];
    CGRect imageFrame = self.contentView.bounds;
//    imageFrame.size.height -= self.view.safeAreaInsets.bottom;
    for (int i = 0; i<[self.photos count]; i++) {
        PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
        imageFrame.origin.x = i * imageFrame.size.width;
        UIView *itemView = nil;
        if (photoAsset.type == PhotoAssetTypePhoto) {
            itemView = [self createImageViewWithFrame:imageFrame photo:photoAsset];
        }
        if (photoAsset.type == PhotoAssetTypeVideo) {
            itemView = [self createPlayerWithFrame:imageFrame photo:photoAsset];
        }
        [self.contentView addSubview:itemView];
        [self.photoViews addObject:itemView];

        
    }
    self.pageControl.numberOfPages = self.photos.count;
    self.contentView.contentSize = CGSizeMake(imageFrame.origin.x+imageFrame.size.width, 0);
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self layoutImageViewsWithAnimate:NO];
}
- (void)layoutImageViewsWithAnimate:(BOOL)anination{
    [UIView animateWithDuration:anination?0.1f:0 animations:^{
        CGRect imageFrame = self.contentView.bounds;
        for (int i = 0; i<self.photoViews.count; i++) {
            BKImageView *imageView = [self.photoViews objectAtIndex:i];
            imageFrame.origin.x = i * imageFrame.size.width;
            imageView.frame = imageFrame;
        }
        self.contentView.contentSize = CGSizeMake(self.contentView.bounds.size.width*self.photos.count, 0);
    }];
    if (self.defaultPage >= 0) {
        CGPoint p = CGPointMake(self.contentView.bounds.size.width * self.defaultPage, 0);
        self.contentView.contentOffset = p;
        self.defaultPage = -1;
    }
}

#pragma Buttons
- (void)toggleNavigationBar{
    BOOL flag = !self.navigationController.navigationBar.hidden;
    [self.navigationController setNavigationBarHidden:flag animated:YES];
}
- (void)clickPhoto:(id)imageView{
    [self toggleNavigationBar];
}

- (void)removePhoto:(id)btn{
    PhotoAsset *photoAsset = [self.photos objectAtIndex:self.pageControl.currentPage];
    NSBlockOperation *op = [self.photoLoadOperationPool objectForKey:photoAsset.asset.localIdentifier];
    if (op) {
        [op cancel];
    }
    //如果是视频则停止播放后再删除
    
    UIView *imageView = [self.photoViews objectAtIndex:self.pageControl.currentPage];
    if([imageView isKindOfClass:[BKPlayerView class]]){
        [(BKPlayerView*)imageView stop];
    }
    //从视图中删除
    [imageView removeFromSuperview];
    
    //从数组中删除照片
    [self.photos removeObjectAtIndex:self.pageControl.currentPage];
    //把元素从列表中删除
    [self.photoViews removeObjectAtIndex:self.pageControl.currentPage];
    
    
    
    if (self.pageControl.numberOfPages == (self.pageControl.currentPage + 1)) {
        self.pageControl.currentPage -= 1;
    }
    self.pageControl.numberOfPages = [self.photos count];
    [self layoutImageViewsWithAnimate:YES];
    if (self.delegate && [self.delegate respondsToSelector:@selector(previewViewController:didRemovePhoto:)]) {
        [self.delegate previewViewController:self didRemovePhoto:photoAsset];
    }
    if (self.photos.count == 0) {
        [self goBack:nil];
    }
}
- (void)goBack:(id)button{
    [self dismissViewControllerAnimated:YES
                             completion:^{
                                 
                             }];
}
#pragma UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int currentPage = (scrollView.contentOffset.x+scrollView.bounds.size.width/2)/scrollView.bounds.size.width;
    if(self.pageControl.currentPage == currentPage){
        return;
    }
//    DLOG(@"scrollViewDidScroll, currentPage:%d", currentPage);
    UIView *preView = [self.photoViews objectAtIndex:self.pageControl.currentPage];
    if([preView isKindOfClass:[BKPlayerView class]]){
        [(BKPlayerView*)preView stop];
    }
    self.pageControl.currentPage = currentPage;
    UIView *imageView = [self.photoViews objectAtIndex:currentPage];
    if([imageView isKindOfClass:[BKPlayerView class]]){
//        [(BKPlayerView*)imageView play];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
